package com.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
 
public class GZipUtils {
	
	
	public static byte[] gzip(byte[] data) throws Exception{
		
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
		gzipOutputStream.write(data);
		gzipOutputStream.finish();
		gzipOutputStream.close();
		byte[] ret = byteArrayOutputStream.toByteArray();
		byteArrayOutputStream.close();
		return ret;
	}
 
	public static byte[] ungzip(byte[] data) throws Exception{
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
		GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
		byte[] buf = new byte[1024];
		int num = -1;
		ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
		while((num = gzipInputStream.read(buf,0,buf.length)) != -1) {
			byteOutputStream.write(buf,0,num);
		}
		gzipInputStream.close();
		byteArrayInputStream.close();
		byte[] ret = byteOutputStream.toByteArray();
		byteOutputStream.flush();
		byteOutputStream.close();
		return ret;
	}
	
	public static void main(String[] arg0) throws Exception{
		
		String readPath = System.getProperty("user.dir")+File.separatorChar+"sources"+File.separatorChar+"001.png";
		File file = new File(readPath);
		FileInputStream inputStream = new FileInputStream(file);
		byte[] data = new byte[inputStream.available()];
		inputStream.read(data);
		inputStream.close();
		
		System.out.println("文件原始大小为："+data.length);
		
		//测试压缩
		byte[] ret1 = GZipUtils.gzip(data);
		System.out.println("压缩之后大小为:"+ret1.length);
		
		//测试还原
		byte[] ret2 = GZipUtils.ungzip(ret1);
		System.out.println("还原时候大小为："+ret2.length);
		
		String writePath = System.getProperty("user.dir")+File.separatorChar+"receive"+File.separatorChar+"001.png";
		FileOutputStream outputStream = new FileOutputStream(writePath);
		outputStream.write(ret2);
		outputStream.close();
	}
}